<template>
  <div>
    <el-card class="box-card" :body-style="{ padding: '10px 10px 2px 10px' }">
      <el-form :inline="true" :model="queryParam" class="demo-form-inline" size="medium">
        <el-form-item label="备份日期">
          <el-date-picker v-model="backupsDate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备份类型">
          <el-select v-model="queryParam.backupsType" placeholder="请选择" clearable>
            <el-option v-for="item in [
              { value: 0, label: '手动备份' },
              { value: 1, label: '自动备份' },
            ]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="loading ? 'el-icon-loading' : 'el-icon-s-check'" @click="handleAdd">{{
            loading ? '备份中' : '立即备份' }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-setting" @click="handleSetting">备份设置</el-button>
        </el-form-item>
        <el-form-item>
          <el-popconfirm title="此操作将恢复数据库到选中文件版本,建议提前手动备份, 是否继续?" @confirm="() => customRecovery()">
            <el-button slot="reference" type="primary">自定义恢复</el-button>
          </el-popconfirm>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="recoveryRecord">恢复记录</el-button>
        </el-form-item>
        <input ref="sqlUploadInput" type="file" accept=".sql" style="display: none" @change="uploadChange" />
      </el-form>
    </el-card>
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <el-table :data="tableData" border style="width: 100%" height="55vh">
        <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
        <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
          :width="item.width">
          <template #default="scope">
            <span v-if="item.prop === 'backupsType'">
              <el-tag v-show="scope.row.backupsType == 0">手动备份</el-tag>
              <el-tag v-show="scope.row.backupsType == 1">自动备份</el-tag>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template slot-scope="{ row }">
            <el-button link size="mini" :icon="row.loading ? 'el-icon-loading' : ' '" @click="handleRecovery(row)">
              {{ row.loading ? '恢复中' : '恢复' }}</el-button>
            <el-button link size="mini" @click="handleEditPath(row)"> 编辑路径</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <pagination ref="pagination" :totalCount="totalCount" @pagination="pagination"></pagination>
    </el-card>
    <el-dialog title="编辑路径" v-model="dialogVisible" width="50%" :before-close="handleClose">
      <el-descriptions class="margin-top" :column="2" border>
        <el-descriptions-item label="备份时间">{{ descriptions.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备份类型">
          <el-tag>{{ descriptions.backupsType == 0 ? '手动备份' : '自动备份' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备份路径">
          <el-input v-model="descriptions.file" placeholder="请输入备份路径"></el-input>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <backup-setting-dialog ref="backupSettingDialog"></backup-setting-dialog>
    <recovery-dialog ref="recoveryDialog"></recovery-dialog>
  </div>
</template>

<script>
import { pageList, backup, recovery, edit, details, customRecovery } from '@/api/sys/backups'
import moment from 'moment/moment'
import backupSettingDialog from './dialog/backupSettingDialog.vue'
import recoveryDialog from './dialog/recoveryDialog.vue'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'backups',
  components: { backupSettingDialog, recoveryDialog },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      totalCount: 0, //总数
      //查询条件
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      queryParam: {},
      backupsDate: [],
      tableData: [],
      tableProps: [
        { title: '备份时间', prop: 'createTime', width: '150' },
        { title: '备份类型', prop: 'backupsType', width: '150' },
        { title: '文件', prop: 'file', width: '' },
      ],
      descriptions: {},
    }
  },
  mounted() {
    this.loadData()
  },

  methods: {
    // 编辑路径
    handleEditPath(row) {
      this.dialogVisible = true
      details(row.id).then((res) => {
        if (res.data.code === 200) {
          this.descriptions = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 编辑提交
    handleSubmit() {
      edit(this.descriptions)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.handleClose()
            this.loadData()
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    handleClose() {
      this.dialogVisible = false
    },

    onSubmit() {
      this.$refs.pagination.resetPagination()
    },
    reset() {
      this.backupsDate = []
      this.queryParam = {}
      this.$refs.pagination.resetPagination()
    },
    handleAdd() {
      this.loading = true
      backup()
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.loadData()
          } else {
            this.$message.error(res.data.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    handleSetting() {
      this.$refs.backupSettingDialog.edit()
    },
    customRecovery() {
      this.$refs.sqlUploadInput.click()
    },
    recoveryRecord() {
      this.$refs.recoveryDialog.init()
    },
    async uploadChange(event) {
      const files = event.target.files
      if (files.length > 0) {
        // 大于0，说明有文件要上传
        // 创建FormData对象
        const data = new FormData()
        // 添加文件
        data.append('file', files[0])
        // 调用接口
        await customRecovery(data)
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.loadData()
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err)
          })
      }
    },
    loadData() {
      if (this.backupsDate != null && this.backupsDate.length > 0) {
        this.queryParam.beginTime = moment(this.backupsDate[0]).format('YYYY-MM-DD 00:00:00')
        this.queryParam.endTime = moment(this.backupsDate[1]).format('YYYY-MM-DD 23:59:59')
      } else {
        this.queryParam.beginTime = null
        this.queryParam.endTime = null
      }
      var param = Object.assign(this.queryParam, this.searchModel)
      pageList(param)
        .then((res) => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.records.map((item) => {
              return {
                loading: false,
                ...item,
              }
            })
            this.totalCount = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    pagination(val) {
      this.searchModel.pageNo = val.page
      this.searchModel.pageSize = val.limit
      this.loadData()
    },
    handleRecovery(row) {
      this.$confirm('此操作将恢复数据库到选中版本, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          row.loading = true
          recovery(row.id).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.loadData()
            } else {
              this.$message.error(res.data.message)
            }
            row.loading = false
          })
        })
        .catch((error) => {
          if (error === 'cancel') {
            // 用户点击了取消按钮，可以在此处添加相应处理逻辑
          } else {
            // 其他错误情况，例如网络错误等
            this.$message.error(error)
          }
        })
    },
  },
}
</script>

<style scoped lang="less"></style>
